package com.greenold.order.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;


import com.greenold.order.dto.OrderDto;
import com.greenold.order.domain.OrderDTO;
import com.greenold.refunds.domain.Refund;
import com.greenold.refunds.service.IRefundService;


import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.greenold.common.annotation.Log;
import com.greenold.common.core.controller.BaseController;
import com.greenold.common.core.domain.AjaxResult;
import com.greenold.common.enums.BusinessType;
import com.greenold.order.domain.Order;
import com.greenold.order.service.IOrderService;
import com.greenold.common.utils.poi.ExcelUtil;
import com.greenold.common.core.page.TableDataInfo;

/**
 * 订单Controller
 *
 * @author ruoyi
 * @date 2025-10-13
 */
@RestController
@RequestMapping("/greenold-order/order")
public class OrderController extends BaseController
{
    @Autowired
    private IOrderService orderService;

    // 新增：注入退款服务
    @Autowired
    private IRefundService refundService;

    /**
     * 查询订单列表
     */
   // @PreAuthorize("@ss.hasPermi('greenold-order:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(Order order)
    {

        startPage();
        List<Order> list = orderService.selectOrderList(order);
        return getDataTable(list);
    }

    /**
     * 查询订单内容
     */
    // @PreAuthorize("@ss.hasPermi('greenold-order:order:list')")
    @GetMapping("/orderInfo")
    public TableDataInfo orderInfo(OrderDTO orderDTO)
    {
        List<OrderDTO> list = orderService.selectOrderInfo(orderDTO);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @PreAuthorize("@ss.hasPermi('greenold-order:order:export')")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Order order)
    {
        List<Order> list = orderService.selectOrderList(order);
        ExcelUtil<Order> util = new ExcelUtil<Order>(Order.class);
        util.exportExcel(response, list, "r订单数据");
    }

    /**
     * 获取订单详细信息
     */
//    @PreAuthorize("@ss.hasPermi('greenold-order:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {

        return success(orderService.selectOrderById(id));
    }

    /**
     * 新增订单
     */
//    @PreAuthorize("@ss.hasPermi('greenold-order:order:add')")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Order order)
    {
        return toAjax(orderService.insertOrder(order));
    }




    /**
     * 修改订单
     */
//    @PreAuthorize("@ss.hasPermi('greenold-order:order:edit')")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Order order)
    {
        return toAjax(orderService.updateOrder(order));
    }

    /**
     * 删除订单
     */
//    @PreAuthorize("@ss.hasPermi('greenold-order:order:remove')")
//    @Log(title = "订单", businessType = BusinessType.DELETE)
//	@DeleteMapping("/{ids}")
//    public AjaxResult remove(@PathVariable String[] ids)
//    {
//        return toAjax(orderService.deleteOrderByIds(ids));
//    }




    /**
     * 取消订单接口（核心：接收前端请求，调用Service更新状态）
     * 前端调用时传递：{ "orderId": "订单ID", "cancelReason": "取消原因" }
     */
//    @PreAuthorize("@ss.hasPermi('greenold-order:order:cancel')") // 权限控制
    @PostMapping("/cancel") // 接口路径，与前端API的url对应
    public AjaxResult cancelOrder(@RequestBody Map<String, String> params) {
        // 1. 从请求参数中获取订单ID和取消原因
        String orderId = params.get("orderId");
        String cancelReason = params.get("cancelReason");

        // 2. 调用Service层的取消订单方法（仅更新状态，不删除）
        int rows = orderService.cancelOrder(orderId, cancelReason);

        // 3. 根据Service返回结果，返回成功/失败信息
        if (rows > 0) {
            return AjaxResult.success("订单取消成功");
        } else {
            return AjaxResult.error("订单取消失败，请检查订单状态");
        }
    }
    /**
     * 订单提交退款（对接前端 refundOrder 调用）
     */
//    @PreAuthorize("@ss.hasPermi('greenold-order:order:refund')")
    @PostMapping("/refund")
    public AjaxResult orderRefund(@RequestBody Map<String, String> params) {
        // 1. 提取前端参数
        String orderId = params.get("orderId");
        String orderStatus = params.get("orderStatus");
        String extend2 = params.get("extend2"); // 退款原因
        String customerName=params.get("customerName");
        // 2. 构造退款对象
        Refund refund = new Refund();
        refund.setOrderId(orderId); // 关联订单ID
        refund.setExtend2(extend2); // 退款原因
        refund.setRefundStatus("0"); // 初始状态：退款中
//        refund.setCustomerName(customerName);
        // 3. 调用退款服务提交申请
        return refundService.applyRefund(refund);
    }

    @GetMapping("/listall")
    public TableDataInfo listAll(Order order) {
        startPage();
        List<OrderDto> orders = orderService.listAll(order);
        return getDataTable(orders);
    }
    @DeleteMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable String id) {
        return orderService.deleteOrderById(id);
    }

    @GetMapping("/QueryOrderId")
    public AjaxResult QueryOrderId(String bizOrderNo) {
        return orderService.QueryOrderId(bizOrderNo);
    }


}
